package com.property.manage.service.rent;


import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.guardchina.framework.mybatis.model.CustomPage;
import com.guardchina.framework.util.exception.BusinessException;
import com.guardchina.framework.util.exception.SystemException;
import com.guardchina.framework.util.utils.DateUtil;
import com.guardchina.framework.util.utils.NumberUtil;
import com.guardchina.framework.util.utils.PhoneUtil;
import com.property.manage.dao.flowingWater.FlowingWaterMapper;
import com.property.manage.dao.rent.RentMapper;
import com.property.manage.model.flowingWater.FlowingMoneyVo;
import com.property.manage.model.flowingWater.FlowingWaterEntity;
import com.property.manage.model.flowingWater.FlowingWaterVo;
import com.property.manage.model.rent.RentEntity;
import com.property.manage.model.rent.RentVo;
import com.property.manage.model.resource.Building;
import com.property.manage.service.fee.CollectionService;
import com.property.manage.service.fee.PropertyService;
import com.property.manage.service.resource.BuildingService;
import lombok.extern.slf4j.Slf4j;
import org.apache.ibatis.annotations.Param;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.time.LocalDate;
import java.util.List;
import java.util.Optional;

/**
 * 描述
 *
 * @author lwb
 * @since 2020/7/15
 */
@Component
@Slf4j
public class RentService {
    @Autowired
    private RentMapper rentMapper;
    @Autowired
    private CollectionService collectionService;
    @Autowired
    private BuildingService buildingService;


    public RentVo findParking(Integer id) {
        RentVo rentVo = rentMapper.queryById(id);
        if (rentVo==null){
            return rentVo;
        }
        if (rentVo.getType()==2){
            Building building = buildingService.findBuilding(rentVo.getBuildingId());
            if (building==null){
                throw new BusinessException("没有查到楼栋信息",String.format("楼栋id[%s]",rentVo.getBuildingId()));
            }
            String number=rentVo.getVillageName()+"小区"+building.getBuilding()+"栋"+building.getUnit()+"单元"+building.getRoomNumber();
            rentVo.setNumber(number);
        }
        return rentVo;
    }

    public RentEntity getById(Integer id){
        RentEntity rentEntity = rentMapper.selectById(id);

        return Optional.ofNullable(rentEntity).orElseThrow(() -> new SystemException("房屋出租信息不存在", String.format("id[%s]", id)));
    }

    public CustomPage<RentVo> page(Long pageNo, Long pageSize, Integer type, Integer villageId, String name) {
        Page<RentVo> page = new Page<>(pageNo, pageSize);
        IPage<RentVo> village = rentMapper.getPage(page, type, villageId, name);
        List<RentVo> records = village.getRecords();
        if (records.isEmpty()) {
            return new CustomPage<>(village);
        }
        for (RentVo record : records) {
            if (record.getType() != 2) {
                continue;
            }
            Building building = buildingService.findBuilding(record.getBuildingId());
            if (building == null) {
                continue;
            }
            String number=record.getVillageName()+"小区"+building.getBuilding()+"栋"+building.getUnit()+"单元"+building.getRoomNumber();
            record.setNumber(number);
        }

        return new CustomPage<>(village);
    }

    @Transactional(rollbackFor = Exception.class)
    public void add(BigDecimal money, LocalDate nextTime, LocalDate startTime, LocalDate endTime, String name, String phone,
                    Integer type, String number, Integer buildingId, Integer villageId
    ) {
        checkData(phone, type, number, buildingId);
        RentEntity entity = new RentEntity();
        entity.setBuildingId(buildingId);
        entity.setEndTime(endTime);
        entity.setPhone(phone);
        entity.setMoney(money);
        entity.setName(name);
        entity.setNumber(number);
        entity.setNextTime(nextTime);
        entity.setStartTime(startTime);
        entity.setVillageId(villageId);
        entity.setType(type);
        entity.setState(RentEntity.STATE_RENTING);
        try {
            rentMapper.insert(entity);
            if (nextTime != null) {
                collectionService.saveOrUpdate(type, entity.getId(), nextTime);
            }
        } catch (Exception e) {
            throw new BusinessException("新增租金管理失败", String.format("新增租金管理失败[%s]", e));
        }
    }


    @Transactional(rollbackFor = Exception.class)
    public void update(Integer id, BigDecimal money, LocalDate nextTime, LocalDate startTime, LocalDate endTime, String name, String phone,
                       Integer type, String number, Integer buildingId, Integer villageId) {
        checkData(phone, type, number, buildingId);
        UpdateWrapper<RentEntity> wrapper = new UpdateWrapper<>();
        wrapper.set("money", money);
        wrapper.set("next_time", nextTime);
        wrapper.set("start_time", startTime);
        wrapper.set("end_time", endTime);
        wrapper.set("name", name);
        wrapper.set("phone", phone);
        wrapper.set("type", type);
        wrapper.set("number", number);
        wrapper.set("building_id", buildingId);
        wrapper.eq("id", id);
        wrapper.set("village_id", villageId);
        try {
            rentMapper.update(null, wrapper);
            if (nextTime != null) {
                collectionService.saveOrUpdate(type, id, nextTime);
            }
        } catch (Exception e) {
            throw new BusinessException("修改租金信息失败", String.format("修改租金信息发送错误[%s]", e));
        }

    }
    @Transactional(rollbackFor = Exception.class)
    public void update(Integer id,Integer type,LocalDate nextTime){
        UpdateWrapper<RentEntity> wrapper = new UpdateWrapper<>();
        wrapper.set("next_time", nextTime);
        wrapper.eq("id", id);
        try {
            rentMapper.update(null, wrapper);
            collectionService.saveOrUpdate(type, id, nextTime);
        } catch (Exception e) {
            throw new BusinessException("修改租金信息失败", String.format("修改租金信息发送错误[%s]", e));
        }
    }

    private void checkData(String phone, Integer type, String number, Integer buildingId) {
        if (!PhoneUtil.isMobile(phone)) {
            throw new BusinessException("请填写正确的手机号码");
        }
        if (type == 2) {
            if (buildingId == null) {
                throw new BusinessException("房屋出租必须传递楼栋信息");
            }
        }
        if (type == 3) {
            if (number == null) {
                throw new BusinessException("房屋出租必须传递楼栋信息");
            }
        }
    }


    public void delete(Integer id) {

        UpdateWrapper<RentEntity> wrapper = new UpdateWrapper<>();
        wrapper.eq("id", id);
        wrapper.set("state", RentEntity.STATE_DELETED);

        rentMapper.update(null, wrapper);
    }

}
